<template>
    <div class="payment-container">
        <!-- 顶部工具栏：按钮右对齐 -->
        <div class="top-bar">
            <div></div> <!-- 左侧占位（可留空） -->
            <div class="action-buttons">
                <el-button class="!ml-0" type="primary" @click="openAddDialog">新增</el-button>
                <el-button @click="batchClose">禁用</el-button>
                <el-button @click="batchOpen">启用</el-button>
                <el-button @click="refresh">刷新</el-button>
            </div>
        </div>

        <!-- 结算方式列表 -->
        <el-table :data="payment" border style="width: 100%" v-loading="tableLoad" highlight-current-row
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="操作" width="120">
                <template #default="{ row }">
                    <el-button size="small" @click="editPaymentMethod(row.id)">
                        <el-icon>
                            <Edit />
                        </el-icon>
                    </el-button>
                    <el-button size="small" @click="deletePaymentMethod(row)">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </el-button>
                </template>
            </el-table-column>

            <el-table-column prop="name" label="名称" width="300" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
                        @change="() => handleStatusChange(row)" />
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑结算方式弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogType ? '编辑结算方式' : '新增结算方式'" width="400px" @close="resetForm">
            <div class="dialog-form">
                <div class="form-item">
                    <label class="label">名称:</label>
                    <el-input v-model="form.name" placeholder="请输入结算方式名称" />
                </div>
            </div>

            <template #footer>
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="savePayment" :loading="saving">
                    {{ dialogType ? '更新' : '保存' }}
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const tableLoad = ref(false)

const saving = ref(false)


// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref(false)


// 数据列表
const payment = ref([])

const getPayment = async () => {
    tableLoad.value = true
    try {

        const res = await axios.get('/api/basic/payment/allPaymentMethod')

        if (res.data.code === 5200) {
            payment.value = res.data.paymentMethodList
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }
}


// 表单数据
const form = ref({ id: '', name: '' })

// 重置表单
const resetForm = () => {
  form.value = { id: '', name: '' }
}

// 打开新增弹窗
const openAddDialog = () => {
    dialogType.value = false
    resetForm()
    dialogVisible.value = true
}

// 编辑结算方式
const editPaymentMethod = async (id) => {
    dialogType.value = true

    try {
        const res = await axios.get('/api/basic/payment/paymentMethodById', { params: { id } })
        if (res.data.code === 5200) {
            form.value = res.data.paymentMethod
            dialogVisible.value = true
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 保存结算方式
const savePayment = async () => {

    try {
        saving.value = true

        if (!form.value.name.trim()) {
            ElMessage.error('请输入品牌名称')
            return
        }

        const url = dialogType.value ? '/api/basic/payment/updatePaymentMethod' : '/api/basic/payment/addPaymentMethod'
        console.log(form.value)

        const res = await axios.post(url, form.value)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            dialogVisible.value = false
            getPayment()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        saving.value = false
    }
}

// 状态变更
const handleStatusChange = async (row) => {
    tableLoad.value = true
    const originalStatus = row.status
    try {
        const res = await axios.post('/api/basic/payment/updatePaymentMethodStatus', null, {
            params: {
                id: row.id,
                status: originalStatus === 1 ? 0 : 1
            }
        })
        if (res.data.code !== 5200) {
            ElMessage.error('状态更新失败')
        } else {
            ElMessage.success('状态更新成功')
            await getPayment()
        }
    } catch (error) {
        ElMessage.error('网络错误，请重试')
    } finally {
        tableLoad.value = false
    }
}

// 选中的对象
const selections = ref([])

// 选中的id
const selectionIds = computed(() => selections.value.map(item => item.id))

// 选中多选框
const handleSelectionChange = (selection) => {
    selections.value = selection
}

// 批量禁用
const batchClose = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {

    const params = {
        ids: selectionIds.value,
        status
    }

    try {
        const res = await axios.post("/api/basic/payment/batchUpdatePaymentMethodStatus", params)
        if (res.data.code === 5200) {
            ElMessage.success("修改成功")
            await getPayment()
        } else {
            ElMessage.error("修改失败")
        }
    } catch (error) {
        ElMessage.error("修改失败")
    }
}

// 删除结算方式
const deletePaymentMethod = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要删除结算方式 "${row.name}" 吗？`, '警告')
    } catch {
        ElMessage.info('已取消删除')
    }

    try {
        const res = await axios.post('/api/basic/payment/deletePaymentMethod', null, { params: { id: row.id } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getPayment()
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 刷新数据
const refresh = () => {
    getPayment()
}

onMounted(() => {
    getPayment()
})

</script>

<style scoped>
.payment-container {
    padding: 20px;
    background-color: #fff;
}

/* 顶部工具栏：左右分布，按钮靠右 */
.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.el-table {
    margin-top: 10px;
}

/* 操作按钮样式 */
.el-button--small {
    padding: 5px 8px;
    font-size: 12px;
}

.dialog-form {
    padding: 20px;
    font-size: 14px;
}

.form-item {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.label {
    width: 100px;
    text-align: right;
    color: #333;
}

.el-input {
    flex: 1;
    max-width: 200px;
}
</style>
